import json
import base64
import cv2
import time
import gluoncv
import numpy as np
import matplotlib
import matplotlib.patches as mpatches
import os


def remote_call(url, pic_name):
    f_register = open(pic_name, 'rb')
    b64_register = base64.b64encode(f_register.read())
    register_data = {"Pic": b64_register.decode()}
    data = json.dumps(register_data)
    import requests
    r=requests.post(url, data)
    return json.loads(r.content)["results"]


def draw_lines(lines, ax):
    for x0, y0, x1, y1, score in lines:
        ax.plot([x0, x1], [y0, y1], '-')


def draw_text(bbox, text_results, ax):
    font = matplotlib.font_manager.FontProperties(fname="fonts/simhei.ttf")
    for n, (x0, y0, x1, y1) in enumerate(bbox):
        ax.text(x0, y1, text_results[n], fontsize=16, color="white", font_properties=font)




if __name__ == '__main__':
    import glob
    import matplotlib.pyplot as plt
    matplotlib.rcParams["font.sans-serif"] = ["SimHei"]
    matplotlib.rcParams["axes.unicode_minus"] = False   #
    line_url = 'http://127.0.0.1:28600/detect_lines'
    text_rcog_url = 'http://127.0.0.1:28601/recog_text'

    folder = '/data1/test_paper_reco_jingyouwang/1st-2st-merged-for-line-detection/val/'
    for item in glob.iglob(folder + '*.jpg'):
        print(item)
        image = cv2.imread(item)[:, :, ::-1]
        lines_results = remote_call(line_url, item)
        fig, axes = plt.subplots(1, 2, squeeze=False)
        axes = axes.reshape(-1)
        axes[0].imshow(image)
        axes[1].imshow(np.zeros_like(image.astype(np.uint8)))
        draw_lines(lines_results, axes[1])

        text_recog_results = ["hello"]
        text_bboxes_processed=[[5,10,15,20]]
        draw_text(text_bboxes_processed, text_recog_results, axes[1])

        plt.tight_layout()
        svg_path = "output/{}.svg".format(os.path.basename(item)[:-4])
        print(svg_path)
        plt.savefig(svg_path)
        plt.show()
